package com.xh.controller;

import cn.hutool.core.io.IoUtil;
import com.xh.model.request.PosterSaveRequest;
import com.xh.model.request.PreviewRequest;
import com.xh.model.response.*;
import com.xh.service.CorePostersService;
import com.xh.service.PostersService;
import com.xh.utils.FileUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.List;

/**
 * @author wen
 * @apiNote
 * @since 2021-07-07
 */
@RestController
@RequestMapping("/api")
public class ApiController {

    @Value("${fileUpload.rootSavePath}")
    private String rootSavePath;
    @Autowired
    private PostersService postersService;
    @Autowired
    private CorePostersService corePostersService;

    /**
     * 图片上传
     */
    @PostMapping("/upload")
    public UploadResponse upload(@RequestParam("file") MultipartFile file) {
        String path = FileUtil.create(rootSavePath, file);
        return UploadResponse.ok(path);
    }

    /**
     * 获取海报记录
     */
    @GetMapping("/user/posters")
    public PosterResponse posters() {
        List<Posters> posters = postersService.getList();
        return PosterResponse.ok(posters);
    }

    /**
     * 保存海报
     */
    @PostMapping("/user/posters")
    public PosterSaveResponse savePoster(@RequestBody PosterSaveRequest request) {
        Long id = postersService.save(request);
        return PosterSaveResponse.ok(id);
    }

    /**
     * 复制海报
     */
    @PostMapping("/user/posters/copy/{id}")
    public PosterSaveResponse savePoster(@PathVariable("id") Long id) {
        Long dbId = postersService.copy(id);
        return PosterSaveResponse.ok(dbId);
    }

    /**
     * 删除海报记录
     */
    @DeleteMapping("/user/posters/{id}")
    public PosterDeleteResponse delete(@PathVariable("id") Long id) {
        postersService.delete(id);
        return PosterDeleteResponse.ok();
    }

    /**
     * 海报预览
     */
    @PostMapping(value = "/preview", produces = MediaType.IMAGE_JPEG_VALUE)
    public byte[] preview(@RequestBody PreviewRequest request) {
        // TODO 生成海报图片
        InputStream inputStream = corePostersService.createPoster(request);
//        File file = new File("F:\\IDEA_2021\\07\\gen-pic-demo\\20210317142940.png");
        return IoUtil.readBytes(inputStream);
    }


}
